#include "head.h"
int sendfd(int sockfd, int fdtosend){
    // struct msghdr
    struct msghdr hdr;
    bzero(&hdr,sizeof(hdr)); //不可省略
    // 消息字段 发送数据时必须有消息正文字段
    char buf[] = "hello"; // 要发送消息的内容
    struct iovec iov[1]; // 离散数据只有一个子区域
    iov[0].iov_base = buf;
    iov[0].iov_len= 5;
    hdr.msg_iov = iov; //把iov数组的信息填入hdr
    hdr.msg_iovlen = 1; 
    // 控制字段
    struct cmsghdr * pcmsg = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int)));
    // data的长度是sizeof(int)
    pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level = SOL_SOCKET;
    pcmsg->cmsg_type = SCM_RIGHTS;//只要填入该选项，说明传递的数据是文件描述符
    *(int *)CMSG_DATA(pcmsg) = fdtosend;//把int的fd填入到data
    hdr.msg_control = pcmsg; // 把pcmsg的信息填入hdr
    hdr.msg_controllen = CMSG_LEN(sizeof(int));
    int ret = sendmsg(sockfd,&hdr,0);
    ERROR_CHECK(ret,-1,"sendmsg");
    return 0;
}
int recvfd(int sockfd, int *pfdtorecv){
    // struct msghdr
    struct msghdr hdr;
    bzero(&hdr,sizeof(hdr)); //不可省略
    // 消息字段 发送数据时必须有消息正文字段
    char buf[6] = {0}; // 先申请内存接收消息正文
    struct iovec iov[1]; // 离散数据只有一个子区域
    iov[0].iov_base = buf;
    iov[0].iov_len= 5;
    hdr.msg_iov = iov; //把iov数组的信息填入hdr
    hdr.msg_iovlen = 1; 
    // 控制字段
    struct cmsghdr * pcmsg = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int)));
    // data的长度是sizeof(int)
    pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level = SOL_SOCKET;
    pcmsg->cmsg_type = SCM_RIGHTS;//只要填入该选项，说明传递的数据是文件描述符
    hdr.msg_control = pcmsg; // 把pcmsg的信息填入hdr
    hdr.msg_controllen = CMSG_LEN(sizeof(int));
    int ret = recvmsg(sockfd,&hdr,0);
    ERROR_CHECK(ret,-1,"sendmsg");
    //printf("buf = %s\n",buf);
    //printf("*data = %d\n", *(int *)CMSG_DATA(pcmsg));
    *pfdtorecv = *(int *)CMSG_DATA(pcmsg);
    return 0;
}
